/**
 * Created by fupeng on 17/3/2.
 *
 * 日期：2017-3-3  by at
 * 描述：短信验证==》 1.注册页面，获得手机号，数据库查询是否存在  1）存在，ajax提醒已存在  2）不存在，插入数据库，插入验证码，过期时间10分钟，记录时间
 *                                                                  插入到数据库中  ---》主键  计算验证码
 *                      2. 表单提交，根据手机查询-------验证码过期，提示重新获得验证码   ；  插入数据跳转页面，注册成功
 *
 */
var captchapng = require('captchapng');

const req = require('request');
var dayu = require('alidayu-node');
var config = require('../../config');
var user = require('../models/UserModel');
//var oauthDao = require('../dao/Oauth2RedisDao');
var oauthDao = require('../dao/OauthDao');
var OAuth = require('wechat-oauth');
var member = require('../models/MemberModel');
var redisTool = require('../../common/utils/redistools.js');
var wechatAPI = require('wechat-api');
var api = new wechatAPI(config.app.appid, config.app.appsecret);
var appUtil = require('../../common/utils/appUtils');
// var logger = require('../../common/Logger/Logger');




var client = new OAuth(config.app.appid, config.app.appsecret, function (openid, callback) {
    // 传入一个根据openid获取对应的全局token的方法
    // 在getUser时会通过该方法来获取token
    oauthDao.getOauth(openid, function (message, result) {
        console.log('save access token to database success.');
        return callback(null, result);
    });
}, function (openid, token, callback) {
    // 请将token存储到全局，跨进程、跨机器级别的全局，比如写到数据库、redis等
    // 这样才能在cluster模式及多机情况下使用，以下为写入到文件的示例
    // 持久化时请注意，每个openid都对应一个唯一的token!
    oauthDao.setOauth(openid, token, function (message) {
        console.log('save access token to database success.');
        return callback(message);
    });
});


var sms = new dayu(config.sms.appkey, config.sms.appsecret);
/**
 * 用户登录公众号即获得openId
 *   from:  RequestLogger.js
 * @param openid
 */

function local(req, res) {
    var smscode = req.body.smscode;
    var phone = req.body.phone;

    smscode = appUtil.validParams(smscode, '0000');
    phone=appUtil.validParams(phone,'0000');

    user.selectByPhone(phone, function (userResult) {
        //  var user = users[0];//存在对象  短信验证
        //mysql数据库转为js日期类型
        if (userResult) {
            var datatime = new Date().getTime();//
            var dtint = parseInt(datatime.toString());
            // var ctint=parseInt()
            var flag = dtint > userResult.createtime && dtint < userResult.expiretime;
            if (flag) {
                //在短信有效期内  跳转到用户中心
                if (smscode == userResult.smscode) {
                    var open_id = req.body.open_id;
                    //
                    // client.getUser(open_id, function (err, result) {
                    //     if (err) {
                    //         res.json({
                    //             status: 'error',
                    //             message: '网页过期，请刷新页面'
                    //         });
                    //     }
                    //     var userInfo = result;
                    //     console.log(userInfo);

                        var userInfo = {
                            openid: open_id,
                            nickname: 'addggoi',
                            sex: 1,
                            language: 'zh_CN',
                            city: 'Pudong New District',
                            province: 'Shanghai',
                            country: 'China',
                            headimgurl: 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLA9XiaIAGSPia79Fvv6P1qgWsLbTw3kBibOLCrct9fsBgIy8eqianVibVha5OzBrJLG0cI5AcE27kYYib8A/0',
                            privilege: 1
                        };
                        if (userInfo) {
                            userInfo.phone_number = phone;
                            console.log([open_id, phone, userInfo]);
                            user.addAndLogin(open_id, phone, userInfo, function (userdata) {
                                if (userdata.isSuccess) {
                                    var textMsg = '恭喜您登录成功。';
                                    api.sendText(open_id,textMsg ,function (err, result) {
                                        if (err) {
                                            // res.send({error: '1',message: 'fail'});
                                            // logger.info(err);
                                        } else {
                                            // res.send({error: '0',message: 'success'});
                                        }
                                    });
                                    res.json({
                                        status: 'success',
                                        message: '登录成功'
                                    })
                                }else{
                                    res.json({
                                        status: 'error',
                                        message: '登录失败'
                                    })
                                }
                            });
                        }
                    // })
                } else {
                    res.json({
                        status: 'error',
                        message: '手机验证码有误'
                    });
                }
            }
        } else {
            res.json({
                status: 'fail',
                message: '请先获取手机验证码'
            })
        }

    });
}
function remote(req, res) {
    var smscode = req.body.smscode;
    var phone = req.body.phone;

    smscode = appUtil.validParams(smscode, '0000');
    phone=appUtil.validParams(phone,'0000');

    user.selectByPhone(phone, function (data) {
        //  var user = users[0];//存在对象  短信验证
        //mysql数据库转为js日期类型
        if (data) {
            var datatime = new Date().getTime();//
            var dtint = parseInt(datatime.toString());
            // var ctint=parseInt()
            var flag = dtint > data.createtime && dtint < data.expiretime;
            if (flag) {
                //在短信有效期内  跳转到用户中心
                if (smscode == data.smscode) {
                    var open_id;
                        open_id = req.signedCookies.openid
                    console.log('========11111111111111111111========',open_id)
                    client.getUser(open_id, function (err, result) {
                        if (err) {
                            res.json({
                                status: 'error',
                                message: '网页过期，请刷新页面'
                            });
                            return;
                        }
                        var userInfo = result;
                        console.log(userInfo);
                        if (userInfo) {
                            userInfo.phone_number = phone;

                            console.log([open_id, phone, userInfo])
                            user.addAndLogin(open_id, phone, userInfo, function (userdata) {
                                if (userdata.isSuccess) {
                                    var textMsg = '恭喜您登录成功。';
                                    api.sendText(open_id,textMsg ,function (err, result) {
                                        if (err) {
                                            // res.send({error: '1',message: 'fail'});
                                            // logger.info(err);
                                        } else {
                                            // res.send({error: '0',message: 'success'});
                                        }
                                    });
                                    res.json({
                                        status: 'success',
                                        message: '登录成功'
                                    })
                                }else{
                                    res.json({
                                        status: 'error',
                                        message: '登录失败'
                                    })
                                }
                            });
                        }
                    })

                } else {
                    res.json({
                        status: 'error',
                        message: '手机验证码有误'
                    });
                }
            }else{
                res.json({
                    status: 'fail',
                    message: '请先获取手机验证码'
                });
            }
        } else {
            res.json({
                status: 'fail',
                message: '请先获取手机验证码'
            });
        }

    });
}

module.exports = {
    // 获得图片验证码
    getCode: function (req, res) {
        var width = 80;
        var height = 40;
        var code = Math.random().toString().substring(2, 6);
        var open_id = req.signedCookies.open_id||req.signedCookies.openid;
        open_id = appUtil.validParams(open_id, '0000');

        var key = 'pic-' + open_id;
        redisTool.set(key, code, 600, function (err, result) {
            if (err) {
                console.log('图片验证码缓存失败')
            } else {
                console.log('图片验证码缓存成功')
            }
        })
        var p = new captchapng(width, height, code);
        p.color(10, 10, 10, 10);
        p.color(80, 80, 80, 255);

        var img = p.getBase64();
        var imgbase64 = new Buffer(img, 'base64');
        res.writeHead(200, {
            'Content-Type': 'image/png'
        });
        res.end(imgbase64);
    },
    // 获得短信验证码
    getSMS: function (req, res) {
        var identifyingcode = req.body.identifyingcode;
        var phone = req.body.phone;
        var open_id = req.body.open_id;

        identifyingcode = appUtil.validParams(identifyingcode, '0000');
        phone = appUtil.validParams(phone, '0000');
        open_id = appUtil.validParams(open_id, '0000');

        //判断验证码是否相同     ====暂缓
        //发送手机短信
        // 短信验证码入库


        function getSMSCode() {
            // console.log(123);
            //随机验证码生成
            // var random=Math.random();
            var code = Math.random().toString().substring(2, 6);
            // 验证码入库   md5加密
            console.log('验证码计算为：' + code);
            return code;
        }

        var pickey = 'pic-' + open_id;
        console.log(pickey);
        redisTool.get(pickey, function (err, result) {
            if (err) {
                res.json({
                    status: error,
                    message: '获取失败'
                });
                console.log("获得图片验证码失败")
            }
            if (result == identifyingcode) {

                var code = getSMSCode();

                user.createSmsCode(code, phone, function (index) {
                    console.log("row:" + index);
                    if (!index.isSuccess) {
                        console.log("logincontroller rows error");
                        return;
                    }
                    //插入成功，发送短信
                    console.log("发送短信");

                    sms.smsSend({
                        sms_free_sign_name: '百视通点播影院', //短信签名，参考这里 http://www.alidayu.com/admin/service/sign
                        sms_param: JSON.stringify({"number": '' + code}),//短信变量，对应短信模板里面的变量
                        rec_num: phone, //接收短信的手机号
                        sms_template_code: 'SMS_56765019' //短信模板，参考这里 http://www.alidayu.com/admin/service/tpl
                    }, function (error, response) {
                        if (!error) {
                            console.log(response);
                            res.json({
                                status: 'error',
                                message: '获取短信验证码失败'
                            });
                        }
                        else {
                            console.log(error);
                            res.json({
                                status: 'success'
                            });
                        }
                    });
                });
            } else {
                res.json({
                    status: 'error',
                    message: '请输入正确的验证码'
                });
            }
        })
    },
    // 验证手机是否已存在
    validPhone: function (req, res) {

        var identifyingcode = req.body.identifyingcode;
        var phone = req.body.phone;
        var sms = req.body.sms;

        //手机号是否存在
        user.selectByPhone(phone, function (users) {
            if (users || users.isSuccess == false) {
                // 不存在手机号，继续；存在，提示

                res.json = {
                    message: 'error',
                    status: 'error',
                    data: ''
                };
                return;
            }

            var user = users[0];//存在对象  短信验证

            //mysql数据库转为js日期类型
            var datatime = new Date('yyyy-MM-dd hh-mm-ss');//
            if (datatime > user.createtime && datetime < user.expiretime) {
                //在短信有效期内
                user.register();
            }


        });
        // 1.判断短信验证码

        // user.validSMS();

        // 2.
    },
// 传入手机号，验证码，验证完成；验证码是否一致，是否过期；过期，重新获取，前台提示；否则，页面跳转----用户中心
    loginConfirm: function (req, res) {
        var smscode = req.body.smscode;
        var phone = req.body.phone;
        //手机号是否存在
    //    local(req, res);
         remote(req, res);
    },


    changePhone: function (req, res) {
        var oldPhone = req.body.oldphonenumber;
        var newPhone = req.body.newphonenumber;
        var smscode = req.body.smscode;
        var open_id = req.body.open_id;

        oldPhone = appUtil.validParams(oldPhone, '0000');
        newPhone = appUtil.validParams(newPhone, '0000');
        smscode = appUtil.validParams(smscode, '0000');
        open_id = appUtil.validParams(open_id, '0000');

        // oldPhone=appUtil


        user.selectByPhone(newPhone, function (data) {
            if (data) {
                var datatime = new Date().getTime();//
                var dtint = parseInt(datatime.toString());
                // var ctint=parseInt()
                var flag = dtint > data.createtime && dtint < data.expiretime;
                if (flag) {
                    //在短信有效期内  开始更换手机号
                    if (smscode == data.smscode) {
                        user.changePhone([oldPhone, newPhone], function (result) {
                            if (result.isSuccess) {
                                //手机号更换成功
                                res.json({
                                    status: 'success',
                                    message: '手机更换成功'
                                })

                            } else {
                                if (result && result.message == '查无手机') {
                                    res.json({
                                        status: 'error',
                                        message: '查无手机'
                                    })
                                } else if (result && result.message == '手机号已经被注册') {
                                    res.json({
                                        status: 'error',
                                        message: '手机号已经被注册'
                                    })
                                } else {
                                    res.json({
                                        status: 'failure',
                                        message: '手机更换失败'
                                    })
                                }
                            }
                        });
                    } else {
                        res.json({
                            status: 'error',
                            message: '手机验证码有误'
                        });
                    }
                }else{
                    res.json({
                        status: 'error',
                        message: '请先获取验证码'
                    })
                }
            } else {
                res.json({
                    status: 'error',
                    message: '请先获取验证码'
                })
            }
        })
    },
    /**
     * 查询会员卡
     * @param req
     * @param res
     */
    getCard: function (req, res) {
        //获得openid
        var ipenid = req.signedCookies.openid;
        ipenid = appUtil.validParams(ipenid, '0000');
        user.getCardIdByUserId(ipenid, function (result) {
            if (result.isSuccess) {
                res.render('membercard', {
                    status: 'success',
                    message: '会员卡',
                     phone:result.phone,
                    cardid: result.cardid
                })
            } else {
                res.render('membercard', {
                    status: 'error',
                      phone:result.phone,
                    message: '无会员卡'
                    //cardid:"暂无会员卡"
                })
            }

        })
    },

    /**
     * 更换用户操作，跟用户注册类似，这里验证手机号是否存在账号：
     * 存在：openid更换
     * 不存在，注册：直接插入一条
     * @param req
     * @param res
     */
    changeUser: function (req, res) {
        var smscode = req.body.smscode;
        var phone = req.body.phone;
        var open_id = '';

        smscode = appUtil.validParams(smscode, '0000');
        phone = appUtil.validParams(phone, '0000');

        //手机号是否存在  redis中
        user.selectByPhone(phone, function (data) {
            //  var user = users[0];//存在对象  短信验证
            //mysql数据库转为js日期类型
            if (data) {
                var datatime = new Date().getTime();//
                var dtint = parseInt(datatime.toString());
                // var ctint=parseInt()
                var flag = dtint > data.createtime && dtint < data.expiretime;
                if (flag) {
                    //在短信有效期内  跳转到用户中心
                    if (smscode == data.smscode) {
                        open_id = req.body.open_id;
                        member.selectByOpenID(open_id, function (member) {
                            if (!member) return;
                            var userInfo = member[0];
                            if (userInfo) {
                                userInfo.phone_number = phone;
                                //先获得openid的
                                user.changeUser([open_id, phone, userInfo], function (result) {
                                    if (result.isSuccess) {
                                        if (result.message=='new'){
                                            var textMsg = '恭喜您登录成功。';
                                            api.sendText(open_id,textMsg ,function (err, result) {
                                                if (err) {
                                                    // res.send({error: '1',message: 'fail'});
                                                    // logger.info(err);
                                                } else {
                                                    // res.send({error: '0',message: 'success'});
                                                }
                                            });
                                        }

                                        res.json({
                                            status: 'success',
                                            message: '更换用户'
                                        })
                                    } else {
                                        res.json({
                                            status: 'error',
                                            message: '更换失败，请重新输入手机号'
                                        });
                                        var i=0;
                                    }
                                });
                            }
                        })
                    } else {
                        res.json({
                            status: 'error',
                            message: '手机验证码有误'
                        });
                    }
                }else{
                    res.json({
                        status: 'error',
                        message: '手机验证码有误'
                    });
                }
            } else {
                res.json({
                    status: 'fail',
                    message: '请先获取手机验证码'
                })
            }

        });
    }

};




